import { get, post } from '@common/ajax';
import urls from '@common/url';
import { GET_RECHARGE_STORE_LIST, GET_PROTOCOL_DETAIL } from '@store/mutationType';
import logger from '@common/logger';

const recharge = {
    state: {
        rechargeStoresList: [],
        rechargeProtocol: null,
    },
    mutations: {
        GET_RECHARGE_STORE_LIST: (state, rechargeStoresList) => {
            Object.assign(state, {
                rechargeStoresList,
            });
        },
        GET_PROTOCOL_DETAIL: (state, rechargeProtocol) => {
            Object.assign(state, {
                rechargeProtocol,
            });
        },
    },
    actions: {
        // 创建充值订单
        createRechargeOrder: async ({ commit }, param) => {
            const res = await post(urls.createRechargeOrder, param);
            logger.success('创建支付订单结果'. res);
            return res;
        },
        // 获取充值预付信息
        createRechargePrepay: async ({ commit }, orderNumber) => {
            const param = {
                order_number: orderNumber,
                store_id: '',
            };
            const res = await post(urls.onlineRechargePrepay, param);
            logger.success('创建预付订单结果：', res);
            return res;
        },
        // 获取可用充值门店的信息
        getRechargeStoresInfo: async ({ commit }, ids=[]) => {
            const res = await get(urls.availableStore, {
                ids: ids.join(','),
            });
            commit(GET_RECHARGE_STORE_LIST, res.stores);
        },
        // 充值完成
        searchRechargeState: async ({ commit }, orderNumber) => {
            const res = await get(urls.searchRecharge, {
                order_number: orderNumber,
                from_success: 1,
                store_id: '',
            });
            return res.accounting_result === 1;
        },
        // 获取充值协议
        getRechargeProtocol: async ({ commit }) => {
            const { has_protocol, protocol } = await get(urls.protocol);
            commit(GET_PROTOCOL_DETAIL, has_protocol ? protocol : has_protocol);
        },
    },
};

export default recharge;
